<template>
  <l-layout class="l-tab-page" v-show="!lr_loadPage" style="border-radius: 8px;">
    <l-panel style="padding: 3px">
      <template #toolLeft>
        <l-breadcrumb :levelList.sync="levelList" @change="handleBreadcrumbChange"></l-breadcrumb>
      </template>
      <template #toolRight>
        <l-tool-btns :hasAdd="false" :hasRefresh="false">
          <template v-if="levelList[0].name == '全部文件'">
            <el-button-group>
              <!-- <el-button size="mini" @click="handleAddFolder()">{{$t('新建文件夹')}}</el-button> -->
            </el-button-group>
            <el-button-group v-if="levelList.length > 1">
              <l-upload ref="uploadFile" :showFileList="false" btnText="上传文件" :limit="1000"
                :accept="appConfig.file.accept" :maxSize="appConfig.file.maxSize" :sizeType="appConfig.file.sizeType"
                :upload="uploadFile" :uploadCallback="uploadCallback" @success="()=>{
                  loadTableData()
                }"></l-upload>
            </el-button-group>
          </template>
        </l-tool-btns>
      </template>

      <l-table :columns="columns" :dataSource="tableData" :loading="tableLoading">
        <template v-slot:name="scope">
          <div class="learun-list-item-wraper">
            <div class="learun-list-item-icon">
              <!-- 文件/文件夹 图标 -->
              <i v-if="scope.row.type == 1" class="el-icon-folder" style="color: #fbbc06;font-size: 20px;"></i>
              <i v-else :class="lr_getFileIcon(scope.row.name).icon"
                :style="{color: lr_getFileIcon(scope.row.name).color,'font-size': '20px'}"></i>
            </div>
            <div class="learun-list-item-content">
              <div class="learun-list-item-title">
                <el-button @click="handleOpenFolder(scope.row)" size="mini" type="text">{{scope.row.name}}</el-button>
              </div>
            </div>
          </div>
        </template>
        <!-- 文件大小 -->
        <template v-slot:size="scope">
          {{scope.row.type == 1?'': $countFileSize(scope.row.size)}}
        </template>
        <!-- 操作按钮 -->
        <l-table-btns :filterBtns="filterBtns" :btns="tableBtns" @click="lr_handleTableBtnClick"
          :isAuth="false"></l-table-btns>
      </l-table>

    </l-panel>

    <!--新增文件夹-->
    <l-dialog :title="$t(folderTitle)" :visible.sync="folderVisible" :height="120" :width="400" @ok="handleFolderSave"
      @close="handleFolderCloseForm" @opened="handleFolderOpenedForm">
      <folder-form ref="folderForm"></folder-form>
    </l-dialog>

    <!--文件预览-->
    <l-fullscreen-dialog :showOk="false" :visible.sync="fileVisible">
      <template #title>
        <div>
          <div v-if="fileData" class="learun-list-item-wraper">
            <div class="learun-list-item-icon">
              <i :class="lr_getFileIcon(fileData.name).icon" :style="{color: lr_getFileIcon(fileData.name).color}"></i>
            </div>
            <div class="learun-list-item-content">
              <div class="learun-list-item-title" style="color: rgba(0,0,0,.85);">
                {{fileData.name}}
              </div>
              <div class="learun-list-item-des">
                {{fileData.level || levelName}}
              </div>
            </div>
          </div>
        </div>
      </template>
      <file-form ref="fileForm" :file="fileData" :level="levelName" @upload="uploadFormFile" @update="updateFormFile">
      </file-form>
    </l-fullscreen-dialog>

    <!--文件命名-->
    <l-dialog :title="$t('重命名')" :visible.sync="fileNameVisible" :height="120" :width="400" @ok="handleFileNameSave"
      @close="handleFileNameCloseForm" @opened="handleFileNameOpenedForm">
      <file-name-form ref="fileNameForm"></file-name-form>
    </l-dialog>

  </l-layout>
</template>
<script>
import FolderForm from './folderForm.vue'
import FileForm from './fileForm.vue'
import FileNameForm from './fileNameForm.vue'

export default {
  components: {
    FolderForm,   // 文件夹命名
    FileForm,     // 文件预览
    FileNameForm, // 文件命名
  },
  props: {
    projectId: {   // 传入当前项目id  即根文件夹id 可获取初始文件夹列表
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      sideList: [],// 左侧文件夹目录
      // 顶部 文件路径
      levelList: [
        {
          name: '全部文件',
          id: this.projectId
        }
      ],
      // table 列表
      columns: [
        { label: '文件名', prop: 'name', minWidth: 200 },
        { label: '最后更新', prop: 'modifyTime', width: 160, dataType: 'datetime' },
      ],
      tableLoading: false,
      tableData: [],

      formEditRow: null,

      folderTitle: '',
      folderVisible: false,
      folderEdit: false,


      fileOption: [], // 文件上传
      fileUploadTimer: null,

      fileVisible: false, // 文件预览
      fileData: null,

      fileNameVisible: false, // 文件命名

      parentId: "",//当前文件夹id
    }
  },
  computed: {
    // 操作按钮
    tableBtns() {
      if (this.disabled) {
        return []
      }
      return [
        { prop: 'Down', label: '下载' },
        { prop: 'Edit', label: '重命名', width: 48 },
        { prop: 'Delete', label: '删除', divided: true }
      ]
    },
    // 文件路径名称
    levelName() {
      const list = this.levelList.map(t => t.name)
      const listStr = String(list)
      return listStr.replace(/,/g, '/')
    }
  },
  mounted() {
  },
  methods: {

    init(data) {
      this.businessId = data.businessId
      this.businessCode = data.businessCode
      this.loadFolderData(true) // 获取初始文件夹目录
    },
    setTableFolder(data) {
      this.tableData = data
    },

    /** 获取初始文件夹目录 */
    async loadFolderData(isFirst) {
      const api = window.$crud('businness/project/archives/schema');
      let queryData = {
        parentId: this.businessId, // 当前业务id
        projectId: this.projectId, // 当前项目id
        configBusinessId: this.businessCode, // 业务表名
      }
      let data = await this.$awaitWraper(api.getInfo(queryData))
      data.forEach(item => {
        item.icon = "el-icon-folder"
        item.label = item.name;
        item.businessCode = item.configBusinessid;
        if (item.type == "Dir") {
          item.type = 1
        }
      });
      this.sideList = data // 添加至左侧文件夹列表

      if (data.length && isFirst) {
        this.levelList = [
          { name: '全部文件', id: this.businessId },
          { name: data[0].name, id: data[0].id }
        ]
        this.loadTableData() // 默认展示第一个文件夹内容
      }
    },

    /** 加载文件夹数据 传入当前文件夹id  */
    async loadTableData() {
      this.tableLoading = true
      // 传参
      const queryData = {
        parentId: this.levelList[this.levelList.length - 1].id,
        configBusinessId: this.businessCode, // 业务表名
        projectId: this.projectId, // 当前项目id
      }
      const api = window.$crud('businness/project/archives/schema');
      let data = await this.$awaitWraper(api.getInfo(queryData))
      if (data) {
        data.forEach(item => {
          item.businessCode = item.configBusinessid;
          if (item.type == "Dir") {
            item.type = 1
          }
        });
      }
      this.tableData = data || []
      this.tableLoading = false
    },

    /** 获取项目文件树 */
    async loadProjectFolder() {
      await this.$awaitWraper(window.$crud("businness/project/archives/dir/schema").getInfo({ projectId: this.projectId })).then((result) => {
        result.forEach(r => {
          r.businessCode = r.configBusinessid
          r.type = 1
        })
        // 加载文件树
        this.tableData = result
        this.levelList = [
          { name: '全部文件', id: 'allProject' }
        ]
      });
    },

    // 按钮过滤
    filterBtns(row, btns) {
      if (row.type == 1 || row.type == 'Dir') {
        // 文件夹 取消下载按钮
        var downBtn = btns.find(t => t.prop == 'Down')
        downBtn && (downBtn.disabled = true)
        return []
      }
      return btns
    },


    //#region 新增 重命名 下载 预览 ··· 按钮事件
    /** 左侧文件夹目录结构 点击事件 */
    handleSideClick(item) {
      this.businessId = item.businessId
      this.businessCode = item.businessCode

      // 初始化文件路径
      this.levelList = [{
        name: '全部文件',
        id: this.projectId
      }]
      // 添加点击的左侧目录结构
      this.levelList.push(item)
      // 获取数据
      this.loadTableData()
    },

    /** 重命名 */
    handleEdit($index, row) {
      this.formEditRow = row
      if (row.type == 1) { // 文件夹
        this.folderEdit = true
        this.showFolderForm(`重命名【${row.name}】`)
      }
      else { // 文件
        this.fileNameVisible = true
      }
    },

    /** 下载 */
    handleDown($index, row) {
      this.$downFile(
        `${this.apiUrl}system/annexesfile/${row.id}?token=${this.token}`
      )
    },

    /** 文件夹管理 新增 */
    handleAddFolder() {
      this.folderEdit = false
      this.showFolderForm('新增文件夹')
    },

    /** 文件/文件夹 预览/打开 */
    handleOpenFolder(row) {
      this.businessId = row.businessId
      this.businessCode = row.businessCode

      if (row.type == 1) {// 文件夹
        let levelList = this.levelList
        if (row.level) {
          levelList = []
          const levelNameList = row.level.split('/')
          const levelIdList = row.levelId.split('/')
          levelNameList.forEach((name, index) => {
            levelList.push({ name: name, id: levelIdList[index] })
          })
        }
        levelList.push({ name: row.name, id: row.id })
        this.levelList = levelList
        this.loadTableData()
      }
      else {// 预览文件
        this.fileData = row
        this.fileVisible = true
      }
    },

    /** 打开弹窗 */
    showFolderForm(text) {
      this.folderTitle = text
      this.folderVisible = true
    },

    /** 文件路径点击 */
    handleBreadcrumbChange(e) {
      if (e.id == 'allProject') {
        this.loadProjectFolder()
        return
      }
      this.loadTableData()
    },

    //#endregion


    //#region 删除
    /** 永久删除 */
    handleDelete($index, row) {
      this.$confirm(`是否删除${row.type == 1 ? '文件夹' : '文件'}【${row.name}】?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res
          if (row.type == 1) { // 文件夹
            const dirApi = window.$crud('dir');
            res = await this.$awaitWraper(dirApi.remove(row.id))
            this.loadFolderData(false)  // 刷新左侧文件夹目录
          }
          else { // 文件
            const api = window.$api.system.file;
            res = await this.$awaitWraper(api.deleteFile(row.id))
          }

          if (res) {
            this.loadTableData()
            this.$message({
              type: "success",
              message: "删除成功!",
            })
          }
        })
        .catch(() => {
        })
    },
    //#endregion


    //#region  文件夹新增/编辑 表单提交、关闭
    /** 文件夹 新增/编辑  接口传参 */
    async handleFolderSave(showLoading, hideLoading) {
      showLoading('保存数据中...')
      // 传入文件夹id  校验是否重复
      if (await this.$refs.folderForm.validateForm(this.folderEdit ? this.formEditRow.pid : this.levelList[this.levelList.length - 1].id)) {
        // 传参
        const res = await this.$refs.folderForm.saveForm({
          keyValue: this.folderEdit ? this.formEditRow.id : '', // 当前文件夹id 编辑传入需要
          pid: this.levelList[this.levelList.length - 1].id, // 父级id
          projectId: this.projectId, // 根级id 即项目id
          businessId: this.businessId,
          levelId: String(this.levelList.map(t => t.id)).replace(/,/g, '/'), // 层级路径
          isEdit: this.folderEdit,
          businessCode: this.businessCode
        })
        if (res) {
          const msg = this.formEdit ? '重命名成功!' : '新增成功!'
          this.$message({
            type: 'success',
            message: this.$t(msg)
          })
          this.loadFolderData(false)  // 刷新左侧文件夹目录
          this.loadTableData()
          this.folderVisible = false
        }
      }
      hideLoading()
    },
    handleFolderCloseForm() {
      this.$refs.folderForm.resetForm()
    },
    handleFolderOpenedForm() {
      if (this.folderEdit) {
        this.$refs.folderForm.setForm({ f_Name: this.formEditRow.name, f_Id: this.formEditRow.id, f_PId: this.formEditRow.pid })
      }
    },
    //#endregion


    //#region 文件命名 表单提交、关闭
    /** 文件命名 接口传参 */
    async handleFileNameSave(showLoading, hideLoading) {
      showLoading('保存数据中...')
      if (await this.$refs.fileNameForm.validateForm()) {
        const res = await this.$refs.fileNameForm.saveForm({
          keyValue: this.formEditRow.fileid
        })
        if (res) {
          const msg = '重命名成功!'
          this.$message({
            type: 'success',
            message: this.$t(msg)
          })
          this.loadTableData()
          this.fileNameVisible = false
        }
      }
      hideLoading()
    },
    handleFileNameCloseForm() {
      this.$refs.fileNameForm.resetForm()
    },
    handleFileNameOpenedForm() {
      this.$refs.fileNameForm.setForm({ f_Name: this.formEditRow.name, f_Id: this.formEditRow.id, f_FolderId: this.formEditRow.pid })
    },
    //#endregion


    //#region 文件上传
    // eslint-disable-next-line
    async uploadCallback(data, param) {
      const postData = {
        folderId: this.levelList[this.levelList.length - 1].id,
        filename: data.filename,
        fileId: data.fileId,
        chunks: data.chunks
      }

      const annexesFileApi = window.$api.system.annexesFile;
      await annexesFileApi.businnessMerge(postData);

      const fileApi = window.$api.system.file;
      const res = await fileApi.add({
        f_FolderId: this.levelList[this.levelList.length - 1].id,
        f_Name: postData.filename,
        f_FileId: postData.fileId,
        f_Keyword: 1
      })
      this.$message({
        type: 'success',
        message: '上传成功！'
      })
      return res
    },

    /**
     * @description: 文件上传
     */
    uploadFile(option) {
      this.fileOption.push(option)
      if (this.fileUploadTimer == null) {
        this.fileUploadTimer = setTimeout(async () => {
          if (this.fileOption.length > 0) {
            // const names = this.fileOption.map(t => t.file.name)
            // 是否重复
            // const api = window.$api.system.file;
            // await this.$awaitWraper(api.getSameFiles(this.levelList[this.levelList.length - 1].id, { ids: String(names) }))

            const fileList = []
            this.fileOption.forEach(item => {
              const file = item.file
              fileList.push(file)
            })
            this.$refs.uploadFile.upLoadFiles(fileList)

            this.fileOption = []
          }
          this.fileUploadTimer = null
        }, 50)
      }
    },
    uploadFormFile(file) {
      this.$refs.uploadFile.upLoadFiles([file])
    },
    updateFormFile(item) {
      this.fileData.name = item.f_Name
      this.fileData.modifyDate = item.f_CreateDate
      this.fileData.size = item.f_FileSize
      this.fileData.version = item.f_Ver
    },
    //#endregion

  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog.is-fullscreen.l-fullscreen-dialog {
  width: 49%;
  height: 96%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
::v-deep .l-layout--container {
  padding-top: 0;
}
.file-name {
  width: 100%;
  // 省略
  white-space: nowrap;
  /*文本不换行*/
  text-overflow: ellipsis;
  /*设置超出部分显示...*/
  overflow: hidden;
  word-break: break-all;
  display: contents;
}
::v-deep .learun-list-item-wraper {
  padding: 0;
}
::v-deep .el-table--border .el-table__cell:first-child .cell {
  padding-left: 7px;
}
.learun-list-item-wraper {
  min-height: 35px;
}
::v-deep td.el-table__cell {
  border: none;
}
::v-deep .l-panel--title {
  line-height: 30px;
  height: 30px;
  border: none;
}
.l-panel--warpper {
  padding-top: 20px;
}
</style>